package com.link.gateway.core.utils;

import com.alibaba.fastjson.JSON;
import com.link.gateway.core.comproperty.InterfaceLogConstants;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author guoshan
 * @date 2019/07/23
 * 处理响应信息：响应内容，响应头
 */
public class ResponseDataUtils {
    /**
     * 向响应头中统一加入编码
     * @param errMsg  要返回的错误信息
     */
    private static byte[] getWrapData(ServerHttpResponse response, String errMsg) {

        HttpHeaders respHeaders = response.getHeaders();
        if (!respHeaders.containsKey("Content-Type")) {
            respHeaders.add("Content-Type","application/json;charset=UTF-8");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success",false);
        map.put("result",errMsg);
        String mapData = JSON.toJSONString(map, false);
        return mapData.getBytes(Charset.forName("utf-8"));

    }

    /**
     * 封装返回数据并且根据标识记录接口日志
     * @author libo
     * @date 2019-08-02
     * @param visitType  访问类型
     * @param errMsg  错误信息
     * @param recordLogFlag  是否记录接口日志信息标识
     * @param exchange 过滤器 的ServerWebExchange对象
     * @return  返回数据
     */
    public static Mono<Void> writeWith(String visitType,
                                       String  errMsg, String recordLogFlag, ServerWebExchange exchange, HttpStatus httpCode) {
        ServerHttpResponse resp = exchange.getResponse();
        if (httpCode != null) {
            resp.setStatusCode(httpCode);
        } else {
            resp.setStatusCode(HttpStatus.PRECONDITION_FAILED);
        }
        exchange.getAttributes().put(InterfaceLogConstants.VISIT_TYPE,visitType);
        exchange.getAttributes().put(InterfaceLogConstants.RECORD_INTERFACE_FLAG,recordLogFlag);
        return resp.writeWith(Flux.just(resp.bufferFactory().wrap(getWrapData(resp, errMsg))));
    }
}
